package com.xuecheng.auth.service.ucenter.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.model.dto.AuthParamsDto;
import com.xuecheng.auth.model.dto.XcUserExt;
import com.xuecheng.auth.model.po.XcUser;
import com.xuecheng.auth.service.checkutils.CheckInsertResultUtil;
import com.xuecheng.auth.service.client.CheckCodeClient;
import com.xuecheng.auth.service.mapper.XcUserMapper;
import com.xuecheng.auth.service.ucenter.AuthService;
import com.xuecheng.base.utils.BeanCopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Slf4j
@Service("password_authservice")
public class UserNameAndPasswordLogin implements AuthService {

    private final XcUserMapper userMapper; // 直接使用Mapper避免Service依赖

    @Autowired
    CheckCodeClient checkCodeClient;
    private final PasswordEncoder passwordEncoder;

    // 使用构造器注入避免循环依赖
    public UserNameAndPasswordLogin(
            XcUserMapper userMapper, CheckCodeClient checkCodeClient,
            PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public XcUserExt execute(AuthParamsDto authParams) {
        CheckInsertResultUtil.checkListExist(() ->{throw new RuntimeException("请输入验证码");},authParams.getCheckcode(),authParams.getCheckcodekey());
        Boolean verify = checkCodeClient.verify(authParams.getCheckcodekey(),authParams.getCheckcode());
        CheckInsertResultUtil.checkBoolean(!verify,()->{throw new RuntimeException("验证码错误");});

        // 使用Mapper查询用户
        XcUser user = userMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, authParams.getUsername()));
        CheckInsertResultUtil.checkExist(user,()->{throw new RuntimeException("用户不存在");});
        if (!passwordEncoder.matches(authParams.getPassword(), user.getPassword())) {
            throw new RuntimeException("账号或密码错误");
        }
        return BeanCopyUtil.copyProperties(user, XcUserExt::new);
    }
}